package spbun.fileclean.listener;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import spbun.fileclean.common.FileUtil;
import spbun.fileclean.dto.FileInfo;

public class BigFileListener {

	public List<FileInfo> list = new ArrayList<>();

	public static void main(String[] args) throws IOException {

		List<FileInfo> files = new BigFileListener().watch("G:\\Work.工作\\SVN\\01、英富森\\2014");

		Collections.sort(files, new Comparator<FileInfo>() {

			@Override
			public int compare(FileInfo o1, FileInfo o2) {
				return (int) (o2.getSize() - o1.getSize());
			}
		});

		for (FileInfo fileInfo : files) {
			System.out.println(FileUtil.getFileSize(fileInfo.getSize()) + "####" + fileInfo.getPath());
		}

	}

	private List<FileInfo> watch(String filePath) throws IOException {

		Path path = Paths.get(filePath);

		int size = 1024 * 1024 * 5;

		SimpleFileVisitor<Path> finder = new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

				File tempFile = file.toFile();

				if (tempFile.length() > size) {
					FileInfo obj = new FileInfo(tempFile.getName(), tempFile.length(), tempFile.getAbsolutePath());
					list.add(obj);
				}

				return super.visitFile(file, attrs);
			}

			@Override
			public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {

				System.out.println("处理文件失败：" + file.toFile());

				return FileVisitResult.CONTINUE;
			}
		};

		java.nio.file.Files.walkFileTree(path, finder);

		return list;
	}
}
